package com.taysear.parcel;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;

import com.taysear.parcel.domain.Account;
import com.taysear.parcel.domain.Customer;
import com.taysear.parcel.domain.Parcel;
import com.taysear.parcel.domain.ParcelAction;
import com.taysear.parcel.domain.ParcelHistory;
import com.taysear.parcel.domain.ParcelStatus;
import com.taysear.parcel.domain.Station;
import com.taysear.parcel.domain.Substation;
import com.taysear.parcel.domain.User;
import com.taysear.parcel.domain.helpers.TParcel;
import com.taysear.parcel.util.Constants;
import com.vaadin.addon.jpacontainer.JPAContainer;
import com.vaadin.addon.jpacontainer.JPAContainerFactory;
import com.vaadin.addon.jpacontainer.JPAContainerItem;
import com.vaadin.addon.tableexport.ExcelExport;
import com.vaadin.data.Container;
import com.vaadin.data.Container.Filter;
import com.vaadin.data.Property.ValueChangeEvent;
import com.vaadin.data.Property.ValueChangeListener;
import com.vaadin.data.util.BeanItem;
import com.vaadin.data.util.BeanItemContainer;
import com.vaadin.data.util.filter.And;
import com.vaadin.data.util.filter.Between;
import com.vaadin.data.util.filter.Compare;
import com.vaadin.data.util.filter.Compare.Equal;
import com.vaadin.data.util.filter.Like;
import com.vaadin.data.util.filter.Not;
import com.vaadin.data.util.filter.Or;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.CheckBox;
import com.vaadin.ui.ComboBox;
import com.vaadin.ui.CustomLayout;
import com.vaadin.ui.DateField;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.TextArea;
import com.vaadin.ui.TextField;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.Window;
import com.vaadin.ui.themes.Reindeer;

@SuppressWarnings("serial")
public class ParcelWindow extends VerticalLayout {
	ParcelApplication app;
	ParcelTable parcelsTable = null;
	JPAContainer<Parcel> parcelsContainer = null;
	MainLayout mainWindow;
	String [] columnsParcelTable = new String[] {"Date", "waybillNumber", "Sender", "Receiver", "Destination", "Status", "Amount"};
	String [] columnsIncommingParcelTable = new String[] {"Date", "waybillNumber", "Sender", "Receiver", "Destination", "Status", "Amount", "Loadingsheet"};
	String [] columnsSalesTable = new String[] {"Date", "Origin", "waybillNumber", "Sender", "Destination", "Receiver", "Qty", "Weight", "Cashier", "Pay Mode", "Account", "VAT", "Amount"};
	
	DateField startDate;
	DateField endDate;
	String stationType;
	String substationType;
	TextField name;
	TextField waybillNr;
	TextField telephone;
	Label label;
	Button viewBtn;
	Button exportBtn;
	Button cancelBtn;
	Button collectBtn;
	Button unlockBtn;
	Button undeliveredBtn;
	Button lostBtn;
	String tableCaption;
	int typeOutgoing = 1;
	int typeIncomming = 2;
	int typeSales = 3;
	int type;
	Boolean salesCancelled;
	ComboBox station;
	ComboBox substation;
	ComboBox cashier;
	ComboBox accountsDropDown;
	CheckBox salesPerDay;
	Equal statusDelivered = new Equal("parcelStatus.parcelStatusId", Constants.PARCEL_STATUS_DELIVERED);
	Equal statusCollected = new Equal("parcelStatus.parcelStatusId", Constants.PARCEL_STATUS_COLLECTED);
	Equal statusCancelled = new Equal("parcelStatus.parcelStatusId", Constants.PARCEL_STATUS_CANCELLED);
	Equal statusLocked = new Equal("parcelStatus.parcelStatusId", Constants.PARCEL_STATUS_LOCKED);
	Equal statusUnLock = new Equal("parcelStatus.parcelStatusId", Constants.PARCEL_STATUS_UNLOCKED);
	private Subject currentUser;

	public ParcelWindow(final ParcelApplication app, MainLayout mainWindow, final int type, final Boolean salesCancelled) {
		this.app = app;
		this.mainWindow = mainWindow;
		setSpacing(true);
		this.type = type;
		this.salesCancelled = salesCancelled;
		this.currentUser = SecurityUtils.getSubject();
		
		CustomLayout parcelWindowLayout = new CustomLayout("manageParcel");
		addComponent(parcelWindowLayout);
		
		VerticalLayout searchVerticalLayout = new VerticalLayout(); 
		searchVerticalLayout.setSpacing(true);
		parcelWindowLayout.addComponent(searchVerticalLayout, "form");
		
		startDate = new DateField("Start");
		startDate.setValue(new Date());
		startDate.setDateFormat(Constants.DATE_FORMAT_STRING);
		startDate.setResolution(DateField.RESOLUTION_DAY);
		
		endDate = new DateField("End");
		endDate.setValue(new Date());
		endDate.setDateFormat(Constants.DATE_FORMAT_STRING);
		endDate.setResolution(DateField.RESOLUTION_DAY);
		
		HorizontalLayout startEndDateLayout = new HorizontalLayout();
		startEndDateLayout.setSizeFull();
		startEndDateLayout.addComponent(startDate);
		startEndDateLayout.addComponent(endDate);
		searchVerticalLayout.addComponent(startEndDateLayout);
		
		HorizontalLayout theRestLayout = new HorizontalLayout();
		theRestLayout.setSizeFull();
		theRestLayout.setSpacing(true);
		searchVerticalLayout.addComponent(theRestLayout);
		
		name = new TextField("Name");
		waybillNr = new TextField("Waybill Number");
		telephone = new TextField("Telephone");
		
		station = new ComboBox("Station");
		JPAContainer<Station> stations = JPAContainerFactory.make(Station.class, app.PERSISTENCE_UNIT);
		Boolean salesStations = currentUser.isPermitted(PermissionsConstants.PERMISSION_PARCEL_SALES_SELECT_STATION);
		Boolean parcelStations = currentUser.isPermitted(PermissionsConstants.PERMISSION_PARCEL_SELECT_STATION);
		if(type == typeSales && !salesStations){
			stations.addContainerFilter(new Equal("stationId", app.getUser().getEmployee().getStation().getStationId()));
			station.setNullSelectionAllowed(false);
		} 
		if(type != typeSales && !parcelStations){
			stations.addContainerFilter(new Equal("stationId", app.getUser().getEmployee().getStation().getStationId()));
			station.setNullSelectionAllowed(false);
		}
		station.setContainerDataSource(stations);
		station.setImmediate(true);
		station.setItemCaptionPropertyId("name");
		station.setValue(app.getUser().getEmployee().getStation().getStationId());
		station.addListener(new ValueChangeListener() {
			@Override
			public void valueChange(ValueChangeEvent event) {
				if(station.getValue() != null){
					fillSubstationDropdown();

					if(type == typeSales){
						loadStationCashiers(((Integer)station.getValue()));
					}
				}
			}
		});
		
		substation = new ComboBox("Substation");
		substation.setImmediate(true);
		substation.setItemCaptionPropertyId("name");
		fillSubstationDropdown();
		substation.addListener(new ValueChangeListener() {
			@Override
			public void valueChange(ValueChangeEvent event) {
				if(substation.getValue() != null){
					if(type == typeSales){
						loadSubstationCashiers();
					}
				}
			}
		});
		
		theRestLayout.addComponent(station);
		theRestLayout.addComponent(substation);
		theRestLayout.addComponent(name);
		theRestLayout.addComponent(waybillNr);
		theRestLayout.addComponent(telephone);
		
		viewBtn = new Button("View");
		viewBtn.addStyleName("greenButton");
		viewBtn.setEnabled(false);
		if (!currentUser.isPermitted(PermissionsConstants.PERMISSION_PARCEL_EDIT))
			viewBtn.setVisible(false);
		viewBtn.setDisableOnClick(true);
		viewBtn.addListener(new ClickListener() {
            public void buttonClick(final ClickEvent event) {
            	if(parcelsTable.getValue() != null)
            		editWindow(parcelsTable.getValue());
            	event.getButton().setEnabled(true);
            }
        });
		cancelBtn = new Button("Cancel");
		cancelBtn.addStyleName("greenButton");
		cancelBtn.setEnabled(false);
		if (!currentUser.isPermitted(PermissionsConstants.PERMISSION_PARCEL_OUTGOING_CANCEL))
			cancelBtn.setVisible(false);
		cancelBtn.setDisableOnClick(true);
		cancelBtn.addListener(new ClickListener() {
            public void buttonClick(final ClickEvent event) {
            	if(parcelsTable.getValue() != null)
            		cancelParcelWindow(parcelsTable.getValue());
            }
        });
		
		collectBtn = new Button("Collect");
		collectBtn.addStyleName("greenButton");
		collectBtn.setEnabled(false);
		if (!currentUser.isPermitted(PermissionsConstants.PERMISSION_PARCEL_INCOMMING_COLLECT))
			collectBtn.setVisible(false);
		collectBtn.setDisableOnClick(true);
		collectBtn.addListener(new ClickListener() {
            public void buttonClick(final ClickEvent event) {
            	if(parcelsTable.getValue() != null)
            		collectParcelWindow(parcelsTable.getValue());
            }
        });
		
		final String salesCancelledText = salesCancelled ? "cancelled" : "";
		exportBtn = new Button("Export to excel");
		exportBtn.addStyleName("greenButton");
		if (!currentUser.isPermitted(PermissionsConstants.PERMISSION_PARCEL_SALES_EXPORT))
			exportBtn.setVisible(false);
		exportBtn.setDisableOnClick(true);
		exportBtn.addListener(new ClickListener() {
            private ExcelExport excelExport;
            public void buttonClick(final ClickEvent event) {
            	excelExport = new ExcelExport(parcelsTable);
                excelExport.setReportTitle("Daily "+ salesCancelledText +"Sales Report");
                excelExport.setDisplayTotals(true);
                excelExport.setExportFileName("daily"+ (salesCancelled ? "_"+ salesCancelledText + "_" : "_") +"sales_report.xls");
                excelExport.export();
                event.getButton().setEnabled(true);
            }
        });
		
		HorizontalLayout actionButtons = new HorizontalLayout();
		actionButtons.setSpacing(true);
		parcelWindowLayout.addComponent(actionButtons, "actionButtons");
		
		actionButtons.addComponent(viewBtn);
		actionButtons.addComponent(cancelBtn);
		actionButtons.addComponent(collectBtn);
		actionButtons.addComponent(exportBtn);
		
		unlockBtn = new Button("Unlock");
		unlockBtn.addStyleName("greenButton");
		unlockBtn.setEnabled(false);
		if (!currentUser.isPermitted(PermissionsConstants.PERMISSION_PARCEL_INCOMMING_UNLOCK))
			unlockBtn.setVisible(false);
		unlockBtn.setDisableOnClick(true);
		unlockBtn.addListener(new ClickListener() {
            public void buttonClick(final ClickEvent event) {
            	if(parcelsTable.getValue() != null)
            		unlockParcelWindow(parcelsTable.getValue());
            }
        });
		actionButtons.addComponent(unlockBtn);
		
		undeliveredBtn = new Button("Undelivered");
		undeliveredBtn.addStyleName("greenButton");
		undeliveredBtn.setEnabled(false);
		if (!currentUser.isPermitted(PermissionsConstants.PERMISSION_PARCEL_SET_UNDELIVERED))
			undeliveredBtn.setVisible(false);
		undeliveredBtn.setDisableOnClick(true);
		undeliveredBtn.addListener(new ClickListener() {
            public void buttonClick(final ClickEvent event) {
            	if(parcelsTable.getValue() != null)
            		undeliverParcelWindow(parcelsTable.getValue());
            }
        });
		actionButtons.addComponent(undeliveredBtn);
		
		lostBtn = new Button("Lost");
		lostBtn.addStyleName("greenButton");
		lostBtn.setEnabled(false);
		if (!currentUser.isPermitted(PermissionsConstants.PERMISSION_PARCEL_SET_LOST))
			lostBtn.setVisible(false);
		lostBtn.setDisableOnClick(true);
		lostBtn.addListener(new ClickListener() {
            public void buttonClick(final ClickEvent event) {
            	if(parcelsTable.getValue() != null)
            		lostParcelWindow(parcelsTable.getValue());
            }
        });
		actionButtons.addComponent(lostBtn);
		
		Date start = app.getStartOfADay(new Date());
		Date end = app.getEndOfADay(new Date());
		Between date = new Between("date", start, end);
		parcelsContainer = JPAContainerFactory.make(Parcel.class, app.PERSISTENCE_UNIT);
		if(type == typeIncomming){
			tableCaption = "All incomming parcels";
			stationType = "receiverStation";
			substationType = "receiverSubstation";
			label = new Label("No incomming parcels found !.");
			Equal sid = mainWindow.equalUserStationId(stationType);
			parcelsContainer.sort(new Object[] { "parcelId" }, new boolean[] {false});
			parcelsContainer.addContainerFilter(new And(sid, statusDelivered));
			parcelsTable = new ParcelTable(app, tableCaption, parcelsContainer, columnsIncommingParcelTable, 0);
			parcelsTable.setSelectable(true);
			parcelsTable.addListener(new ValueChangeListener() {
				@Override
				public void valueChange(ValueChangeEvent event) {
                	enableCancelButton();
                	enableCollectButton();
                	enableLostButton();
                	enableUndeliverButton();
                	enableUnlockButton();
	                enableViewButton();
	            }
	        });
		}
		else if(type == typeOutgoing){
			tableCaption = "All outgoing parcels";
			stationType = "senderStation";
			substationType = "senderSubstation";
			label = new Label("No outgoing parcels found !.");
			Equal sid = mainWindow.equalUserStationId(stationType);
			parcelsContainer.sort(new Object[] { "parcelId" }, new boolean[] {false});
			parcelsContainer.addContainerFilter(new And(sid, date));
			parcelsTable = new ParcelTable(app, tableCaption, parcelsContainer, columnsParcelTable, 0);
			parcelsTable.setSelectable(true);
			parcelsTable.addListener(new ValueChangeListener() {
				@Override
				public void valueChange(ValueChangeEvent event) {
                	enableCancelButton();
                	enableCollectButton();
                	enableLostButton();
                	enableUndeliverButton();
                	enableUnlockButton();
	                enableViewButton();
	            }
	        });
		}
		else if(type == typeSales){
			HorizontalLayout cashierAccountLayout = new HorizontalLayout();
			cashierAccountLayout.setSpacing(true);
			searchVerticalLayout.addComponent(cashierAccountLayout);
			
			cashier = new ComboBox("Cashier");
			cashier.setImmediate(true);
			cashier.addListener(new ValueChangeListener() {
				@Override
				public void valueChange(ValueChangeEvent event) {
					if(event.getProperty().getValue() != null) {
						accountsDropDown.setValue(null);
					}
				}
			});
			cashier.setItemCaptionMode(ComboBox.ITEM_CAPTION_MODE_ITEM);
			loadStationCashiers((Integer)station.getValue());
			cashierAccountLayout.addComponent(cashier);
			
			JPAContainer<Account> accountsContainer = JPAContainerFactory.make(Account.class, app.PERSISTENCE_UNIT);
			accountsDropDown = new ComboBox("Customer accounts");
			if (!currentUser.isPermitted(PermissionsConstants.PERMISSION_PARCEL_SALES_ACCOUNTS))
				accountsDropDown.setVisible(false);
			accountsDropDown.setImmediate(true);
			accountsDropDown.addListener(new ValueChangeListener() {
				@Override
				public void valueChange(ValueChangeEvent event) {
					if(event.getProperty().getValue() != null) {
						cashier.setValue(null);
					}
				}
			});
			accountsDropDown.setItemCaptionMode(ComboBox.ITEM_CAPTION_MODE_ITEM);
			accountsDropDown.setContainerDataSource(accountsContainer);
			cashierAccountLayout.addComponent(accountsDropDown);
			
			salesPerDay = new CheckBox("Show sales per day");
			salesPerDay.setImmediate(true);
			salesPerDay.addListener(new ValueChangeListener() {
				@Override
				public void valueChange(ValueChangeEvent event) {
					if(event.getProperty().getValue() != null) {
						
					}
				}
			});
			startEndDateLayout.addComponent(salesPerDay);
			
			tableCaption = salesCancelledText+" sales";
			stationType = "senderStation";
			substationType = "senderSubstation";
			label = new Label("There are no "+salesCancelledText+" sales for this range !.");
			Equal sid = mainWindow.equalUserStationId(stationType);
			if(salesCancelled)
				parcelsContainer.addContainerFilter(new And(sid, date, statusCancelled));
			else
				parcelsContainer.addContainerFilter(new And(sid, date, new Not(statusCancelled)));
			parcelsContainer.sort(new Object[] { "parcelId" }, new boolean[] {false});
			parcelsTable = new ParcelTable(app, tableCaption, parcelsContainer, columnsSalesTable, 0);
		}
		
		Button search = new Button("Search");
		search.addStyleName("blueButton");
		search.setDisableOnClick(true);
		search.addListener(new ClickListener() {
            public void buttonClick(final ClickEvent event) {
            	searchParcels();
            	event.getButton().setEnabled(true);
            }
        });
		searchVerticalLayout.addComponent(search);
		
		searchVerticalLayout.addComponent(label);
		parcelWindowLayout.addComponent(parcelsTable, "result");
		loadData(parcelsContainer);
	}
	
	private void fillSubstationDropdown(){
		if(station.getValue() != null){
			JPAContainer<Substation> container = JPAContainerFactory.make(Substation.class, app.PERSISTENCE_UNIT);
			Integer sid = (Integer) station.getValue();
			Boolean salesSubstations = currentUser.isPermitted(PermissionsConstants.PERMISSION_PARCEL_SALES_SELECT_SUBSTATION);
			Boolean parcelSubstations = currentUser.isPermitted(PermissionsConstants.PERMISSION_PARCEL_SELECT_SUBSTATION);
			
			
			if(type == typeSales && salesSubstations){
				container.addContainerFilter(new Equal("station.stationId", sid));
			} else if(type != typeSales && parcelSubstations){
				container.addContainerFilter(new Equal("station.stationId", sid));
			} else {
				container.addContainerFilter(new Equal("substationId", app.getUser().getEmployee().getSubstation().getSubstationId()));
				substation.setValue(container.getItemIds().iterator().next());
				substation.setNullSelectionAllowed(false);
			}
			substation.setContainerDataSource(container);
		}
	}
		
	private void loadSubstationCashiers(){
		if(substation.getValue() != null && currentUser.isPermitted(PermissionsConstants.PERMISSION_PARCEL_SALES_SELECT_CASHIERS_SUBSTATION)){
			JPAContainer<User> users = getUsers();
			cashier.setContainerDataSource(users);
			users.addContainerFilter(new Equal("employee.substation.substationId", substation.getValue()));
		}
	}
	
	private void loadStationCashiers(int id){
		JPAContainer<User> users = getUsers();
		cashier.setContainerDataSource(users);
		if(currentUser.isPermitted(PermissionsConstants.PERMISSION_PARCEL_SALES_SELECT_CASHIERS_STATION)){
			users.addContainerFilter(new Equal("employee.station.stationId", id));
		} else {
			users.addContainerFilter(new Equal("userId", app.getUser().getUserId()));
			cashier.setValue(users.getItemIds().iterator().next());
		}
	}
	
	/**
	 * Gets all the users except the admin user.
	 * 
	 * @return JPAContainer<User>
	 */
	private JPAContainer<User> getUsers() {
		JPAContainer<User> users = JPAContainerFactory.make(User.class, app.PERSISTENCE_UNIT);
		users.addContainerFilter(new Not(new Equal("employee.employeeType.employeeTypeId", 99)));
		return users;
	}
	
	private void cancelParcelWindow(final Object selected){
		final Window editWindow = new Window("Cancel parcel");
    	
    	VerticalLayout verticalLayout = (VerticalLayout) editWindow.getContent();
		verticalLayout.setMargin(true);
        verticalLayout.setSpacing(true);
		verticalLayout.setSizeUndefined();
		
		final TextArea description = new TextArea("Description");
		description.setNullRepresentation("");
		description.setWidth(Constants.COMMON_FIELD_WIDTH);
		verticalLayout.addComponent(description);
		
		HorizontalLayout buttons = new HorizontalLayout();
		Button save = new Button("Save");
		save.addStyleName("blueButton");
		save.setDisableOnClick(true);
		save.addListener(new Button.ClickListener() {
            public void buttonClick(ClickEvent event) {
            	EntityManager em = app.em;
        		try{
        			em.getTransaction().begin();
        			Parcel parcel = em.find(Parcel.class, selected);
        			em.refresh(parcel);
        			int status = parcel.getParcelStatus().getParcelStatusId();
        			ParcelStatus parcelStatus = em.find(ParcelStatus.class, Constants.PARCEL_STATUS_CANCELLED);
        			if(status == Constants.PARCEL_STATUS_NEW | status == Constants.PARCEL_STATUS_EDITED | status == Constants.PARCEL_STATUS_UNLOADED){
        				parcel.setParcelStatus(parcelStatus);
        				em.merge(parcel);
        				
        				ParcelAction parcelAction = em.find(ParcelAction.class, Constants.PARCEL_ACTION_CANCEL);
        				String desc = description.getValue() == null ? "" : description.getValue().toString();
        				saveParcelHistory(em, parcel, app.getUser(), parcelAction, "Cancel parcel, description: "+desc);
        				app.showNotification("Parcel is cancelled");
        			} else {
        				String statusDesc = parcel.getParcelStatus().getDescription();
        				app.showNotification("Parcel with status "+statusDesc+" can't be cancelled");
        				throw new Exception("Parcel can't be cancelled");
        			}
        			em.getTransaction().commit();
        		} catch (Exception e) {
        			app.showNotification("Oooopss something whent wrong !!..");
        			em.getTransaction().rollback();
        		}
        		searchParcels();
        		(editWindow.getParent()).removeWindow(editWindow);
            }
        });
		buttons.addComponent(save);
    	
		Button close = new Button("Close");
		close.addStyleName("grayButton");
		close.addListener(new Button.ClickListener() {
            public void buttonClick(ClickEvent event) {
                (editWindow.getParent()).removeWindow(editWindow);
            }
        });
        buttons.addComponent(close);
        verticalLayout.addComponent(buttons);
		
    	editWindow.center();
    	editWindow.setModal(true);
    	getApplication().getMainWindow().addWindow(editWindow);
	}
	
	private void unlockParcelWindow(final Object selected){
		final Window editWindow = new Window("Unlock parcel");
    	
    	VerticalLayout verticalLayout = (VerticalLayout) editWindow.getContent();
		verticalLayout.setMargin(true);
        verticalLayout.setSpacing(true);
		verticalLayout.setSizeUndefined();
		
		final TextArea description = new TextArea("Description");
		description.setNullRepresentation("");
		description.setWidth(Constants.COMMON_FIELD_WIDTH);
		verticalLayout.addComponent(description);
		
		HorizontalLayout buttons = new HorizontalLayout();
		Button save = new Button("Save");
		save.addStyleName("blueButton");
		save.setDisableOnClick(true);
		save.addListener(new Button.ClickListener() {
            public void buttonClick(ClickEvent event) {
            	EntityManager em = app.em;
        		try{
        			em.getTransaction().begin();
        			Parcel parcel = em.find(Parcel.class, selected);
        			em.refresh(parcel);
        			int status = parcel.getParcelStatus().getParcelStatusId();
        			ParcelStatus parcelStatus = em.find(ParcelStatus.class, Constants.PARCEL_STATUS_UNLOCKED);
        			if(status == Constants.PARCEL_STATUS_LOCKED){
        				parcel.setParcelStatus(parcelStatus);
        				parcel.setVerificationAttempts(0);
        				parcel.setVerificationLock(false);
        				em.merge(parcel);
        				
        				ParcelAction parcelAction = em.find(ParcelAction.class, Constants.PARCEL_ACTION_UNLOCK);
        				String desc = description.getValue() == null ? "" : description.getValue().toString();
        				saveParcelHistory(em, parcel, app.getUser(), parcelAction, desc);
        				app.showNotification("Parcel is unlocked");
        			} else {
        				String statusDesc = parcel.getParcelStatus().getDescription();
        				app.showNotification("Parcel with status "+statusDesc+" can't be unlocked");
        				throw new Exception("Parcel can't be unlocked");
        			}
        			em.getTransaction().commit();
        		} catch (Exception e) {
        			app.showNotification("Oooopss something whent wrong !!..");
        			em.getTransaction().rollback();
        		}
        		searchParcels();
        		(editWindow.getParent()).removeWindow(editWindow);
            }
        });
		buttons.addComponent(save);
    	
		Button close = new Button("Close");
		close.addStyleName("grayButton");
		close.addListener(new Button.ClickListener() {
            public void buttonClick(ClickEvent event) {
                (editWindow.getParent()).removeWindow(editWindow);
            }
        });
        buttons.addComponent(close);
        verticalLayout.addComponent(buttons);
		
    	editWindow.center();
    	editWindow.setModal(true);
    	getApplication().getMainWindow().addWindow(editWindow);
	}
	
	private void undeliverParcelWindow(final Object selected){
		final Window editWindow = new Window("Undelivered parcel");
    	
    	VerticalLayout verticalLayout = (VerticalLayout) editWindow.getContent();
		verticalLayout.setMargin(true);
        verticalLayout.setSpacing(true);
		verticalLayout.setSizeUndefined();
		
		final TextArea description = new TextArea("Description");
		description.setNullRepresentation("");
		description.setWidth(Constants.COMMON_FIELD_WIDTH);
		verticalLayout.addComponent(description);
		
		HorizontalLayout buttons = new HorizontalLayout();
		Button save = new Button("Save");
		save.addStyleName("blueButton");
		save.setDisableOnClick(true);
		save.addListener(new Button.ClickListener() {
            public void buttonClick(ClickEvent event) {
            	EntityManager em = app.em;
        		try{
        			em.getTransaction().begin();
        			Parcel parcel = em.find(Parcel.class, selected);
        			em.refresh(parcel);
        			int status = parcel.getParcelStatus().getParcelStatusId();
        			ParcelStatus parcelStatus = em.find(ParcelStatus.class, Constants.PARCEL_STATUS_UNDELIVERED);
        			if(status == Constants.PARCEL_STATUS_LOADED){
        				parcel.setParcelStatus(parcelStatus);
        				parcel.setLoadingsheet(null);
        				em.merge(parcel);
        				
        				ParcelAction parcelAction = em.find(ParcelAction.class, Constants.PARCEL_ACTION_UNLOAD);
        				String desc = description.getValue() == null ? "" : description.getValue().toString();
        				saveParcelHistory(em, parcel, app.getUser(), parcelAction, "Undelivered parcel, description: "+desc);
        				app.showNotification("Parcel is set to undelivered");
        			} else {
        				String statusDesc = parcel.getParcelStatus().getDescription();
        				app.showNotification("Parcel with status "+statusDesc+" can't be set to undelivered");
        				throw new Exception("Parcel can't be set to undelivered");
        			}
        			em.getTransaction().commit();
        		} catch (Exception e) {
        			app.showNotification("Oooopss something whent wrong !!..");
        			em.getTransaction().rollback();
        		}
        		searchParcels();
        		(editWindow.getParent()).removeWindow(editWindow);
            }
        });
		buttons.addComponent(save);
    	
		Button close = new Button("Close");
		close.addStyleName("grayButton");
		close.addListener(new Button.ClickListener() {
            public void buttonClick(ClickEvent event) {
                (editWindow.getParent()).removeWindow(editWindow);
            }
        });
        buttons.addComponent(close);
        verticalLayout.addComponent(buttons);
		
    	editWindow.center();
    	editWindow.setModal(true);
    	getApplication().getMainWindow().addWindow(editWindow);
	}
	
	private void lostParcelWindow(final Object selected){
		final Window editWindow = new Window("Lost parcel");
    	
    	VerticalLayout verticalLayout = (VerticalLayout) editWindow.getContent();
		verticalLayout.setMargin(true);
        verticalLayout.setSpacing(true);
		verticalLayout.setSizeUndefined();
		
		final TextArea description = new TextArea("Description");
		description.setNullRepresentation("");
		description.setWidth(Constants.COMMON_FIELD_WIDTH);
		verticalLayout.addComponent(description);
		
		HorizontalLayout buttons = new HorizontalLayout();
		Button save = new Button("Save");
		save.addStyleName("blueButton");
		save.setDisableOnClick(true);
		save.addListener(new Button.ClickListener() {
            public void buttonClick(ClickEvent event) {
            	EntityManager em = app.em;
        		try{
        			em.getTransaction().begin();
        			Parcel parcel = em.find(Parcel.class, selected);
        			em.refresh(parcel);
        			int status = parcel.getParcelStatus().getParcelStatusId();
        			ParcelStatus parcelStatus = em.find(ParcelStatus.class, Constants.PARCEL_STATUS_LOST);
        			if(status == Constants.PARCEL_STATUS_LOADED){
        				parcel.setParcelStatus(parcelStatus);
        				parcel.setLoadingsheet(null);
        				em.merge(parcel);
        				
        				ParcelAction parcelAction = em.find(ParcelAction.class, Constants.PARCEL_ACTION_UNLOAD);
        				String desc = description.getValue() == null ? "" : description.getValue().toString();
        				saveParcelHistory(em, parcel, app.getUser(), parcelAction, "Lost parcel, description: "+desc);
        				app.showNotification("Parcel is set to lost");
        			} else {
        				String statusDesc = parcel.getParcelStatus().getDescription();
        				app.showNotification("Parcel with status "+statusDesc+" can't be set to lost");
        				throw new Exception("Parcel can't be set to lost");
        			}
        			em.getTransaction().commit();
        		} catch (Exception e) {
        			app.showNotification("Oooopss something whent wrong !!..");
        			em.getTransaction().rollback();
        		}
        		searchParcels();
        		(editWindow.getParent()).removeWindow(editWindow);
            }
        });
		buttons.addComponent(save);
    	
		Button close = new Button("Close");
		close.addStyleName("grayButton");
		close.addListener(new Button.ClickListener() {
            public void buttonClick(ClickEvent event) {
                (editWindow.getParent()).removeWindow(editWindow);
            }
        });
        buttons.addComponent(close);
        verticalLayout.addComponent(buttons);
		
    	editWindow.center();
    	editWindow.setModal(true);
    	getApplication().getMainWindow().addWindow(editWindow);
	}
	
	private void collectParcelWindow(Object selected){
		final Window editWindow = new Window("Collect parcel");
    	
    	VerticalLayout verticalLayout = (VerticalLayout) editWindow.getContent();
		verticalLayout.setMargin(true);
        verticalLayout.setSpacing(true);
		verticalLayout.setSizeUndefined();
		
		Parcel p = app.em.find(Parcel.class, selected);
		app.em.refresh(p);
		TParcel tp = new TParcel();
		tp.setId(p.getParcelId());
    	tp.setStation(p.getParcelDetail().getSenderStation().getStationId());
    	tp.setSubStation(p.getParcelDetail().getSenderSubstation().getSubstationId());
    	tp.setSenderName(p.getParcelDetail().getSenderName());
    	tp.setSenderTel(p.getParcelDetail().getSenderTel());
    	tp.setSenderIdentification(p.getParcelDetail().getSenderIdentification());
    	tp.setDestination(p.getParcelDetail().getReceiverStation().getStationId());
    	if(p.getParcelDetail().getReceiverSubstation() != null)
    		tp.setDestinationSubstation(p.getParcelDetail().getReceiverSubstation().getSubstationId());
    	else 
    		tp.setDestinationSubstation(app.getUser().getEmployee().getSubstation().getSubstationId());
    	tp.setReceiverName(p.getParcelDetail().getReceiverName());
    	tp.setReceiverTel(p.getParcelDetail().getReceiverTel());
    	tp.setReceiverIdentification(p.getParcelDetail().getReceiverIdentification());
    	tp.setParcelType(p.getParcelType().getParcelTypeId());
    	tp.setQuantity(p.getQuantity());
    	tp.setWeight(p.getWeight());
    	tp.setDescription("");
    	tp.setVerificationCode("");
		
    	ParcelForm form = new ParcelForm(app, this, "", 4);
    	form.tp = tp;
    	form.initForm();
		
        verticalLayout.addComponent(form);
		
    	editWindow.center();
    	editWindow.setModal(true);
    	getApplication().getMainWindow().addWindow(editWindow);
	}
	
	private void saveParcelHistory(EntityManager em, Parcel parcel, User user, ParcelAction parcelAction, String desc){ 
		ParcelHistory parcelHistory = new ParcelHistory();
		parcelHistory.setParcel(parcel);
		parcelHistory.setUser(user);
		Date date = new Date();
		parcelHistory.setDate(date);
		parcelHistory.setParcelAction(parcelAction);
		parcelHistory.setDescription(desc);
		em.persist(parcelHistory);
	}
	
	private void enableViewButton(){
		if(parcelsTable.getValue() != null) {
			viewBtn.setEnabled(true);
		} else {
			viewBtn.setEnabled(false);
		}
	}
	
	private void enableLostButton(){
		if(parcelsTable.getValue() != null) {
			Parcel parcel = ((JPAContainerItem<Parcel>) parcelsTable.getItem(parcelsTable.getValue())).getEntity();
			int status = parcel.getParcelStatus().getParcelStatusId();
			if(status == Constants.PARCEL_STATUS_LOADED)
				lostBtn.setEnabled(true);
			else 
				lostBtn.setEnabled(false);
		} else {
			lostBtn.setEnabled(false);
		}
	}
	
	private void enableCancelButton(){
		if(parcelsTable.getValue() != null) {
			Parcel parcel = ((JPAContainerItem<Parcel>) parcelsTable.getItem(parcelsTable.getValue())).getEntity();
			int status = parcel.getParcelStatus().getParcelStatusId();
			if(status == Constants.PARCEL_STATUS_NEW | status == Constants.PARCEL_STATUS_EDITED | status == Constants.PARCEL_STATUS_UNLOADED)
				cancelBtn.setEnabled(true);
			else 
				cancelBtn.setEnabled(false);
		} else {
			cancelBtn.setEnabled(false);
		}
	}
	
	private void enableCollectButton(){
		if(parcelsTable.getValue() != null) {
			Parcel parcel = ((JPAContainerItem<Parcel>) parcelsTable.getItem(parcelsTable.getValue())).getEntity();
			Boolean delivered = parcel.getParcelStatus().getParcelStatusId() == Constants.PARCEL_STATUS_DELIVERED;
			Boolean unlocked = parcel.getParcelStatus().getParcelStatusId() == Constants.PARCEL_STATUS_UNLOCKED;
			if(delivered | unlocked)
				collectBtn.setEnabled(true);
			else 
				collectBtn.setEnabled(false);
		} else {
			collectBtn.setEnabled(false);
		}
	}
	
	private void enableUnlockButton(){
		if(parcelsTable.getValue() != null) {
			Parcel parcel = ((JPAContainerItem<Parcel>) parcelsTable.getItem(parcelsTable.getValue())).getEntity();
			if(parcel.getParcelStatus().getParcelStatusId() == Constants.PARCEL_STATUS_LOCKED)
				unlockBtn.setEnabled(true);
			else 
				unlockBtn.setEnabled(false);
		} else {
			unlockBtn.setEnabled(false);
		}
	}
	
	private void enableUndeliverButton(){
		if(parcelsTable.getValue() != null) {
			Parcel parcel = ((JPAContainerItem<Parcel>) parcelsTable.getItem(parcelsTable.getValue())).getEntity();
			if(parcel.getParcelStatus().getParcelStatusId() == Constants.PARCEL_STATUS_LOADED)
				undeliveredBtn.setEnabled(true);
			else 
				undeliveredBtn.setEnabled(false);
		} else {
			undeliveredBtn.setEnabled(false);
		}
	}
	
	protected void searchParcels() {
		if(checkDates()) {
			if(type == typeSales && salesPerDay.getValue() != null && (Boolean) salesPerDay.getValue()) {
				BeanItemContainer<Parcel> container = new BeanItemContainer<Parcel>(Parcel.class);
				
				String start = app.formatDateForDB(getStartDate());
		    	String end = app.formatDateForDB(getEndDate());
		    	
				String query = " select parcelId, p.date, sum(vatAmount) vatAmount, sum(amount) amount from parcel p, " +
						" parcel_detail pd, parcel_history ph " +
						" where p.parcelDetail = pd.parcelDetailId and p.parcelId = ph.parcel " +
						" and p.date between '"+start+"' and '"+end+"' ";
				if(station.getValue() != null)
					query += " and senderStation =  "+ station.getValue().toString()+" ";
				if(substation.getValue() != null)
					query += " and senderSubstation = "+ substation.getValue().toString()+" ";
				if(cashier.getValue() != null)
					query += " and p.user = "+ cashier.getValue().toString()+" ";
				if(accountsDropDown.getValue() != null)
					query += " and p.account = "+ accountsDropDown.getValue().toString()+" ";
				if(salesCancelled)
					query += " and parcelStatus = "+ Constants.PARCEL_STATUS_CANCELLED+" ";
				else
					query += " and parcelStatus != "+ Constants.PARCEL_STATUS_CANCELLED+" ";
				
				query += " group by date(p.date) ";
				
				List<Object> resultList = new ArrayList<Object>();
				resultList = app.em.createNativeQuery(query).getResultList();
				for (Object object : resultList) {
					Parcel parcel = new Parcel();
					parcel.setParcelId((Integer)((Object[]) object)[0]);
					parcel.setDate((Timestamp)((Object[]) object)[1]);
					parcel.setVatAmount((Double)((Object[]) object)[2]);
					parcel.setAmount((Double)((Object[]) object)[3]);
					container.addBean(parcel);
				}
				loadData(container);
			} else {
				JPAContainer<Parcel> container = JPAContainerFactory.make(Parcel.class, app.PERSISTENCE_UNIT);
				
				Equal sid = null;
				Equal subid = null;
				if(station.getValue() != null)
					sid = new Equal("parcelDetail."+stationType+".stationId",station.getValue());
				
				if(!app.isEmpty(substation.getValue()))
					subid = new Equal("parcelDetail."+substationType+".substationId",substation.getValue());
				
				if(type == typeSales) {
					Equal cid = null;
					Equal selectedAccount = null;
					if(!app.isEmpty(cashier.getValue()))
						cid = new Equal("user.userId", cashier.getValue());
					if(!app.isEmpty(accountsDropDown.getValue()))
						selectedAccount = new Equal("account.accountId", accountsDropDown.getValue());
					if(salesCancelled){
						if(subid == null)
							if(cid == null)
								if(selectedAccount == null)
									if(sid == null)
										container.addContainerFilter(statusCancelled);
									else
										container.addContainerFilter(new And(sid, statusCancelled));
								else
									if(sid == null)
										container.addContainerFilter(new And(selectedAccount, statusCancelled));
									else
										container.addContainerFilter(new And(sid, selectedAccount, statusCancelled));
							else
								if(sid == null)
									container.addContainerFilter(new And(cid, statusCancelled));
								else
									container.addContainerFilter(new And(sid, cid, statusCancelled));
						else
							if(cid == null)
								if(selectedAccount == null)
									if(sid == null)
										container.addContainerFilter(new And(subid, statusCancelled));
									else
										container.addContainerFilter(new And(sid, subid, statusCancelled));
								else
									if(sid == null)
										container.addContainerFilter(new And(subid, selectedAccount, statusCancelled));
									else
										container.addContainerFilter(new And(sid, subid, selectedAccount, statusCancelled));
							else
								if(sid == null)
									container.addContainerFilter(new And(subid, cid, statusCancelled));
								else
									container.addContainerFilter(new And(sid, subid, cid, statusCancelled));
					} else{
						if(subid == null)
							if(cid == null)
								if(selectedAccount == null)
									if(sid == null)
										container.addContainerFilter(new Not(statusCancelled));
									else
										container.addContainerFilter(new And(sid, new Not(statusCancelled)));
								else
									if(sid == null)
										container.addContainerFilter(new And(selectedAccount, new Not(statusCancelled)));
									else
										container.addContainerFilter(new And(sid, selectedAccount, new Not(statusCancelled)));
							else
								if(sid == null)
									container.addContainerFilter(new And(cid, new Not(statusCancelled)));
								else
									container.addContainerFilter(new And(sid, cid, new Not(statusCancelled)));
						else
							if(cid == null)
								if(selectedAccount == null)
									if(sid == null)
										container.addContainerFilter(new And(subid, new Not(statusCancelled)));
									else
										container.addContainerFilter(new And(sid, subid, new Not(statusCancelled)));
								else
									if(sid == null)
										container.addContainerFilter(new And(subid, selectedAccount, new Not(statusCancelled)));
									else
										container.addContainerFilter(new And(sid, subid, selectedAccount, new Not(statusCancelled)));
							else
								if(sid == null)
									container.addContainerFilter(new And(subid, cid, new Not(statusCancelled)));
								else
									container.addContainerFilter(new And(sid, subid, cid, new Not(statusCancelled)));
					}
				}		
				if(type == typeIncomming){
					if(subid == null)
						if(sid != null)
							container.addContainerFilter(new And(sid, new Or(statusDelivered, statusCollected, statusLocked, statusUnLock)));
					else
						if(sid != null)
							container.addContainerFilter(new And(sid, subid, new Or(statusDelivered, statusCollected, statusLocked, statusUnLock)));
				}
				
				if(type == typeOutgoing){
					if(subid == null)
						if(sid != null)
							container.addContainerFilter(new And(sid));
					else
						if(sid != null)
							container.addContainerFilter(new And(sid, subid));
				}
				container.sort(new Object[] { "parcelId" }, new boolean[] {false});
				
				Date start = getStartDate();
		    	Date end = getEndDate();
		    	
		    	Filter date = null;
				if(start != null && end != null && start.compareTo(end) == 1){
					app.showNotification("Invalid Input: Please ensure that start date is before end date.");
					return;
				}
				else { 
					if(start != null && end == null){
						date = new Compare.GreaterOrEqual("date", start);
						container.addContainerFilter(date);
					}
					else if(start == null && end != null){
						date = new Compare.LessOrEqual("date", end);
						container.addContainerFilter(date);
					}
					else if(start != null && end != null){
						date = new Between("date", start, end);
						container.addContainerFilter(date);
					}
				}
				
				String tel = formatStringForLike(telephone.getValue().toString());
				if(tel != null && !"".equalsIgnoreCase(tel)){
					Like senderTel = new Like("parcelDetail.senderTel", tel, false);
					Like receiverTel = new Like("parcelDetail.receiverTel", tel, false);
					container.addContainerFilter(new Or(senderTel, receiverTel));
				}
				String name = formatStringForLike(this.name.getValue().toString());
				if(name != null && !"".equalsIgnoreCase(name)){
					Like senderName = new Like("parcelDetail.senderName", name, false);
					Like receiverName = new Like("parcelDetail.receiverName", name, false);
					container.addContainerFilter(new Or(senderName, receiverName));
				}
				String waybill = formatStringForLike(this.waybillNr.getValue().toString());
				if(waybill != null && !"".equalsIgnoreCase(waybill)){
					Like w = new Like("waybillNumber", waybill, false);
					container.addContainerFilter(w);
				}
				loadData(container);
			}
		}
    }
	
	private Boolean checkDates() {
		Boolean result = false;
		if(startDate.getValue() == null | endDate.getValue() == null){
			app.showNotification("Start date and end date are required.");
		} else {
			Date start = getStartDate();
			Date end = getEndDate();
			Boolean isBefore = start.before(end);
			Boolean isEqual = start.equals(end);
			int comp = start.compareTo(end);
			
			if(start != null && end != null && start.compareTo(end) != 1) {
				result = true;
				int s = start.getMonth();
				int e = end.getMonth();
			} else {
				app.showNotification("Start date should be before or equal to end date.");
			}
		}
		return result;
	}
	
	private Date getStartDate() {
		Date date = null;
    	if(startDate.getValue() != null){
    		try{
	    		date = app.getStartOfADay((Date)startDate.getValue());
	    	} catch (Exception e) {
	    		app.showNotification("Invalid Input: Please ensure that start date is a valid date.");
	    		return date;
			}
    	}
    	return date;
	}
	
	private Date getEndDate() {
		Date date = null;
		if(endDate.getValue() != null){
    		try{
    			date = app.getEndOfADay((Date)endDate.getValue());
	    	} catch (Exception e) {
	    		app.showNotification("Invalid Input: Please ensure that end date is a valid date.");
	    		return date;
			}
    	}
    	return date;
	}
	
	private void loadData(Container container){
		if(container.size() == 0) {
			label.setVisible(true);
			viewBtn.setVisible(false);
			cancelBtn.setVisible(false);
			unlockBtn.setVisible(false);
			collectBtn.setVisible(false);
			exportBtn.setVisible(false);
			undeliveredBtn.setVisible(false);
			lostBtn.setVisible(false);
			parcelsTable.setVisible(false);
		}else {
			label.setVisible(false);
			parcelsTable.setVisible(true);
			parcelsTable.setContainerDataSource(container);
			if (currentUser.isPermitted(PermissionsConstants.PERMISSION_PARCEL_SET_UNDELIVERED))
				undeliveredBtn.setVisible(true);
			if (currentUser.isPermitted(PermissionsConstants.PERMISSION_PARCEL_SET_LOST))
				lostBtn.setVisible(true);
			if(type == typeSales) {
				if (currentUser.isPermitted(PermissionsConstants.PERMISSION_PARCEL_SALES_EXPORT))
					exportBtn.setVisible(true);
				if (currentUser.isPermitted(PermissionsConstants.PERMISSION_PARCEL_INCOMMING_COLLECT))
					collectBtn.setVisible(false);
				if (currentUser.isPermitted(PermissionsConstants.PERMISSION_PARCEL_OUTGOING_CANCEL))
					cancelBtn.setVisible(false);
				viewBtn.setVisible(false);
				undeliveredBtn.setVisible(false);
				lostBtn.setVisible(false);
				parcelsTable.setVisibleColumns(columnsSalesTable);
				fillTableFooter(container);
			} else {
				viewBtn.setVisible(true);
				undeliveredBtn.setVisible(true);
				lostBtn.setVisible(true);
				if (currentUser.isPermitted(PermissionsConstants.PERMISSION_PARCEL_SALES_EXPORT))
					exportBtn.setVisible(false);
				parcelsTable.setVisibleColumns(columnsParcelTable);
			}
			if(type == typeOutgoing) {
				if (currentUser.isPermitted(PermissionsConstants.PERMISSION_PARCEL_OUTGOING_CANCEL)){
					cancelBtn.setVisible(true);
				}
				if (currentUser.isPermitted(PermissionsConstants.PERMISSION_PARCEL_INCOMMING_COLLECT))
					collectBtn.setVisible(false);
			}
			if(type == typeIncomming) {
				if (currentUser.isPermitted(PermissionsConstants.PERMISSION_PARCEL_INCOMMING_UNLOCK)){
					unlockBtn.setVisible(true);
				}
				if (currentUser.isPermitted(PermissionsConstants.PERMISSION_PARCEL_INCOMMING_COLLECT)){
					collectBtn.setVisible(true);
				}
				if (currentUser.isPermitted(PermissionsConstants.PERMISSION_PARCEL_OUTGOING_CANCEL))
					cancelBtn.setVisible(false);
			}
			parcelsTable.requestRepaint();
		}
	}
	
	private void fillTableFooter(Container container){
		Double amount = 0.0;
		Double vatAmount = 0.0;
		if(container.getClass() == BeanItemContainer.class) {
			for (Object o : container.getItemIds()) {
				Parcel p = ((BeanItem<Parcel>) container.getItem(o)).getBean();
				amount += p.getAmount();
				vatAmount += p.getVatAmount();
			}
		}
		if(container.getClass() == JPAContainer.class) {
			JPAContainer<Parcel> c = (JPAContainer<Parcel>) container;
			for (Object o : c.getItemIds()) {
				Parcel p = c.getItem(o).getEntity();
				amount += p.getAmount();
				vatAmount += p.getVatAmount();
			}
		}
			
		parcelsTable.setColumnFooter("Date", "Totals ");
		parcelsTable.setColumnFooter("Amount", new BigDecimal(amount).setScale(2, BigDecimal.ROUND_HALF_DOWN).toString());
		parcelsTable.setColumnFooter("VAT", new BigDecimal(vatAmount).setScale(2, BigDecimal.ROUND_HALF_DOWN).toString());
		parcelsTable.setFooterVisible(true);
	}
	
	private String formatStringForLike(String value){
		String result = value == null | "".equalsIgnoreCase(value) ? "" : "%"+value+"%"; 
		return result;
	}
	
	private void editWindow(Object selected){
    	Parcel p = app.em.find(Parcel.class, selected);
    	TParcel tp = new TParcel(); 
    	tp.setId(p.getParcelId());
    	tp.setStation(p.getParcelDetail().getSenderStation().getStationId());
    	tp.setSubStation(p.getParcelDetail().getSenderSubstation().getSubstationId());
    	tp.setSenderName(p.getParcelDetail().getSenderName());
    	tp.setSenderTel(p.getParcelDetail().getSenderTel());
    	tp.setSenderIdentification(p.getParcelDetail().getSenderIdentification());
    	tp.setDestination(p.getParcelDetail().getReceiverStation().getStationId());
    	if(p.getParcelDetail().getReceiverSubstation() != null)
    		tp.setDestinationSubstation(p.getParcelDetail().getReceiverSubstation().getSubstationId());
    	tp.setReceiverName(p.getParcelDetail().getReceiverName());
    	tp.setReceiverTel(p.getParcelDetail().getReceiverTel());
    	tp.setReceiverIdentification(p.getParcelDetail().getReceiverIdentification());
    	tp.setPaymentMode(p.getPaymentMode().getPaymentModeId());
    	tp.setParcelType(p.getParcelType().getParcelTypeId());
    	tp.setQuantity(p.getQuantity());
    	tp.setWeight(p.getWeight());
    	tp.setAmount(p.getAmount());
    	tp.setVatable(p.getVatable());
    	tp.setVatAmount(p.getVatAmount());
    	tp.setDescription(p.getDescription());
		tp.setVerificationCode(p.getVerificationCode());
		Customer sender = p.getParcelDetail().getSender();
		if(sender != null){
			Account account = (Account) app.em.createQuery("SELECT a FROM Account a Where a.customer.customerId = " + sender.getCustomerId()).getSingleResult();
			tp.setAccount(account.getAccountId());
		}
		
    	ParcelForm form = null;
    	int status = p.getParcelStatus().getParcelStatusId(); 
    	Boolean isNew = status == Constants.PARCEL_STATUS_NEW;
    	Boolean isEdited = status == Constants.PARCEL_STATUS_EDITED;
    	Boolean isUnloaded = status == Constants.PARCEL_STATUS_UNLOADED;
    	if(isNew | isEdited | isUnloaded && currentUser.isPermitted(PermissionsConstants.PERMISSION_PARCEL_EDIT)) {
    		form = new ParcelForm(app, this, "Edit parcel", 3);
    		form.save.setVisible(true);
    	}
    	else {
    		form = new ParcelForm(app, this, "Vieuw parcel", 2);
    		form.save.setVisible(false);
    	}	    	
    	form.tp = tp;
    	form.initForm();
    	
    	Window editWindow = new Window();
    	editWindow.center();
    	editWindow.setModal(true);
		VerticalLayout verticalLayout = (VerticalLayout) editWindow.getContent();
		verticalLayout.setMargin(true);
        verticalLayout.setSpacing(true);
		verticalLayout.setSizeUndefined();
    	verticalLayout.addComponent(form);
    	getApplication().getMainWindow().addWindow(editWindow);
	}
}